package com.xtm.exercise.utils;

import io.jsonwebtoken.*;
import org.springframework.util.StringUtils;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;
import java.util.Random;

/**
 * token管理
 */
public class JwtUtils {

    public static final long EXPIRE = 1000 * 60 * 60 * 24;
    //编码密匙
    public static final String tokenSignKey = "ukc8BDbRigUDaY6pZFfWus2jZWLPHO";
//    private static String tokenSignKey = "123456";

    //1.使用jwt根据用户信息生成token
    public static String getJwtToken(String id,String username, String nickname){

        String JwtToken = Jwts.builder()
                .setHeaderParam("typ", "JWT")
                .setHeaderParam("alg", "HS256")
                .setSubject("guli-user")
                .setIssuedAt(new Date())
                .setExpiration(new Date(System.currentTimeMillis() + EXPIRE))
                .claim("id", id)
                .claim("nickname", nickname)
                .claim("createTime", System.currentTimeMillis())
                .claim("username",username)
                .signWith(SignatureAlgorithm.HS256, tokenSignKey)
                .compressWith(CompressionCodecs.GZIP)
                .compact();
        return JwtToken;
    }

    /**
     * 判断token是否存在与有效
     * @param jwtToken
     * @return
     */
    public static boolean checkToken(String jwtToken) {
        if(StringUtils.isEmpty(jwtToken)) return false;
        try {
            Jwts.parser().setSigningKey(tokenSignKey).parseClaimsJws(jwtToken);
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
        return true;
    }

    /**
     * 判断token是否存在与有效
     * @param request
     * @return
     */
    public static boolean checkToken(HttpServletRequest request) {
        try {
            String jwtToken = request.getHeader("Authorization");
            if(StringUtils.isEmpty(jwtToken)) return false;
            Jwts.parser().setSigningKey(tokenSignKey).parseClaimsJws(jwtToken);
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
        return true;
    }


    /**
     * 根据token获取Claims  获取具体claim   claims.get("id")
     * @param
     * @return
     */
    public static Claims getClaimsByJwtToken(String jwtToken) {
        Jws<Claims> claimsJws = Jwts.parser().setSigningKey(tokenSignKey).parseClaimsJws(jwtToken);
        Claims claims = claimsJws.getBody();
        return claims;
    }

    /**
     * 根据token获取Subject
     * @param
     * @return
     */
    public static String getSubjectByJwtToken(String jwtToken) {
        String subject = Jwts.parser().setSigningKey(tokenSignKey).parseClaimsJws(jwtToken).getBody().getSubject();
        return subject;
    }

    /**
     * 根据token获取会员id
     * @param
     * @return
     */
//    public static String getMemberIdByJwtToken(HttpServletRequest request) {
//        String jwtToken = request.getHeader("Authorization");
//        if(StringUtils.isEmpty(jwtToken)) return "";
//        Jws<Claims> claimsJws = Jwts.parser().setSigningKey(tokenSignKey).parseClaimsJws(jwtToken);
//        Claims claims = claimsJws.getBody();
//        return (String)claims.get("id");
//    }

    //2.根据token字符串得到用户信息
//    public static String getUserFromToken(String token) {
//        String userIfo = Jwts.parser().setSigningKey(tokenSignKey).parseClaimsJws(token).getBody().getSubject();
//        return userIfo;
//    }

    //3.删除token
    public static void removeToken(String token) {
        //jwttoken无需删除，客户端扔掉即可。
    }

    /**
     * 获取混淆MD5签名用的随机字符串
     */
    public static String getRandomKey() {
        return getRandomString(6);
    }

    /**
     * 获取随机位数的字符串
     */
    public static String getRandomString(int length) {
        final String base = "abcdefghijklmnopqrstuvwxyz0123456789";
        Random random = new Random();
        StringBuffer sb = new StringBuffer();
        for (int i = 0; i < length; i++) {
            int number = random.nextInt(base.length());
            sb.append(base.charAt(number));
        }
        return sb.toString();
    }
}
